package handler

import (
	"ecommerce-customer-support-chat/api/request"
	"ecommerce-customer-support-chat/consts"
	"ecommerce-customer-support-chat/internal/dao"
	"ecommerce-customer-support-chat/internal/model"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	jwt2 "github.com/golangblogs/gojwt"
	"net/http"
	"time"
)

func Register(c *gin.Context) {
	var req request.Register
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "参数验证",
			"data": err.Error(),
		})
		return
	}

	user := dao.GetUserBy(req.UserName)
	if user.Id != 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "账号不存在",
			"data": nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "注册成功",
		"data": dao.Create(&model.User{
			UserName: req.UserName,
			Password: req.Password,
		}),
	})

}

func Login(c *gin.Context) {
	var req request.Login
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "参数验证",
			"data": err.Error(),
		})
		return
	}

	user := dao.GetUserBy(req.UserName)
	if user.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "账号不存在",
			"data": nil,
		})
		return
	}

	token, _ := jwt2.NewJWT(consts.JWT_KEY).CreateToken(jwt2.CustomClaims{
		ID: user.Id,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Unix() + 86400,
		},
	})

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": token,
	})

}
